﻿using System;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Web.Helpers;
using ABC.Business.Models;
using ABC.Core.Configuration;


namespace ABC.Business.Web.Handlers
{
    public class YandexImageHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var query = DecodingQueryParam(context.Request.QueryString["q"]);
            int width, height;
            string dir;
            dir = query["dir"];
            int.TryParse(query["width"], out width);
            int.TryParse(query["height"], out height);
            var yandexDiskModel = IoC.Resolve<YandexDiskModel>();
            var file = yandexDiskModel.DownloadFile(dir);
            var webImage = new WebImage(file);

            if (webImage.Height > 0)
            {
                if (webImage.Width > width)
                {
                    webImage.Resize(width, ((width * webImage.Height) / webImage.Width));
                }
                if (webImage.Height > height)
                {
                    webImage.Resize((height * webImage.Width) / webImage.Height, height);
                }
            }

            context.Response.ContentType = "image/jpeg";
            context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(10));
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetMaxAge(TimeSpan.FromMinutes(10));
            context.Response.Cache.SetValidUntilExpires(false);
            context.Response.OutputStream.Write(webImage.GetBytes(), 0, webImage.GetBytes().Length);
            context.Response.End();
        }

        private NameValueCollection DecodingQueryParam(string query)
        {
            query = Encoding.UTF8.GetString(Convert.FromBase64String(query));
            return HttpUtility.ParseQueryString(query);
        }
    }
}
